/**
 * New node file
 */

var API = require('wechat-enterprise').API;

module.exports = (function(){
	
	//Wechat Api
	var wxapi = null;
	
	/**
	 * Handle weixin errors.
	 */
	function handleWxError(err, cb) {

		if (err) {
			sails.log.error(err);
		}
		return cb(new Error(err));

	};
	
	function getOneFromArray(array,id){
		if(array == null || !array.length){
			return null;
		}
		for (var i = 0; i < array.length; i++) {
			if(array[i].id == id){
				return array[i];
			}
		}
		return null;
	}
	
	
	
	var wechat = {
		
		init : function (config){
			
			wxapi = new API(config.corpid, config.secret, config.agentid);
			
		},
		
		findUser : function(connection, collection, options, cb){
			var where = options.where;
			sails.log.info('Call weixin api : [ getDepartmentUsers ]');
			
			try{
				wxapi.getDepartmentUsersDetail(1, 1, 0, function(err, result) {

					if (!err && result.errcode == 0) {
						sails.log.info('Call weixin api success : [ getDepartmentUsers ]');
						return cb(null, result.userlist);
					} else {
						return handleWxError(err, cb);
					}

				});
			}catch(e){
				return cb(e);
			}
		},
		
		findOneUser : function(connection, collection, options, cb){
			var where = options.where;
			sails.log.info('Call weixin api : [ getUser ]');
			
			try{
				wxapi.getUser(where.userid, function(err, result) {
					if (!err && result.errcode == 0) {
						sails.log.info('Call weixin api success : [ getUser ]');
						return cb(null, result);
					} else {
						return handleWxError(err, cb);
					}
				});
			}catch(e){
				return cb(e);
			}
		},
		
		findDepartment : function(connection, collection, options, cb){
			sails.log.info('Call weixin api : [ getDepartments ]');
			
			try{
				wxapi.getDepartments(function(err, result) {
					if (!err && result.errcode == 0) {
						sails.log.info('Call weixin api success : [ getDepartments ]');
						return cb(null, result.department);
					} else {
						return handleWxError(err, cb);
					}
				});
			}catch(e){
				return cb(e);
			}
			
		},
		
		findOneDepartment : function(connection, collection, options, cb){
			sails.log.info('Call weixin api : [ getDepartment ]');
			
			try{
				wechat.findDepartment(connection, collection, options, function(err, result){
					var where = options.where;
					var dept = getOneFromArray(result, where.id);
					if(dept != null){
						wxapi.getDepartmentUsersDetail(where.id, 0, 0, function(err, details) {
							if(details.userlist){
								dept.userlist = details.userlist;
							}
							return cb(null, dept); 
						})
					}else{
						return cb(new Error('Can not find department [id:'+ where.id +']'));
					}
				});
			}catch(e){
				return cb(e);
			}
			
		}
	}
	
	return wechat;
	
})();
